/*
 *@(#)HttpUtil.java 1.0 Mar 13, 2008
 *Copyright Fution Bai
 *
 */
package codebush.util;

import java.sql.CallableStatement;
import java.sql.SQLException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

/**
 * 
 * @author Fution Bai
 * @since 1.0
 */
public class HttpUtil {

	public static Cookie generateRememberMeCookie(String name, int value) {
		return generateRememberMeCookie(name, new Integer(value).toString());

	}

	public static Cookie generateRememberMeCookie(String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath("/");
		cookie.setMaxAge(23328023);// 3600*24*270+23 = 23 328 023
									// 9 months and 23 days 
		return cookie;
	}

	/**
	 * get userId, email, userName from the session
	 * 
	 * @param session
	 * @return
	 */
	public static int getUserId(HttpSession session) {
		if (session.getAttribute("userId") == null) {
			return 0;
		}
		return Integer.parseInt(session.getAttribute("userId").toString());
	}

	public static String getUserName(HttpSession session) {
		return (String) session.getAttribute("userName");
	}

	public static String getEmail(HttpSession session) {
		return (String) session.getAttribute("email");
	}

	public static CallableStatement getCallableStatement(DataSource dataSource, String sql) {
		try {
			return dataSource.getConnection().prepareCall(sql);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

}
